import { NextRequest, NextResponse } from 'next/server'
import { getUserFromRequest } from '@/lib/auth'
import FileManager from '@/lib/fileManager'
import AliyunOSSService from '@/lib/aliyunOSS'

export async function POST(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const body = await request.json()
    const { 
      maxAge = 60 * 60 * 1000, // 默认1小时
      cleanupLocal = true,
      cleanupOSS = true 
    } = body

    const results = {
      localFiles: 0,
      ossFiles: 0,
      errors: [] as string[]
    }

    // 清理本地文件
    if (cleanupLocal) {
      try {
        const fileManager = new FileManager()
        results.localFiles = fileManager.cleanupExpiredFiles(maxAge)
      } catch (error) {
        const errorMsg = `清理本地文件失败: ${error instanceof Error ? error.message : 'Unknown error'}`
        results.errors.push(errorMsg)
        console.error(errorMsg)
      }
    }

    // 清理OSS文件
    if (cleanupOSS) {
      try {
        const ossService = new AliyunOSSService()
        results.ossFiles = await ossService.cleanupExpiredFiles('sensevoice-audio', maxAge)
      } catch (error) {
        const errorMsg = `清理OSS文件失败: ${error instanceof Error ? error.message : 'OSS服务未配置'}`
        results.errors.push(errorMsg)
        console.error(errorMsg)
      }
    }
    
    return NextResponse.json({
      success: true,
      message: `清理完成 - 本地文件: ${results.localFiles}个, OSS文件: ${results.ossFiles}个`,
      results
    })

  } catch (error) {
    console.error('文件清理API错误:', error)
    return NextResponse.json(
      { error: '清理失败' },
      { status: 500 }
    )
  }
}

export async function GET(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const stats = {
      local: { fileCount: 0, totalSize: 0, tempDir: '', configured: false },
      oss: { configured: false, error: null as string | null }
    }

    // 检查本地文件状态
    try {
      const fileManager = new FileManager()
      const localStats = fileManager.getDirectoryStats()
      stats.local = {
        ...localStats,
        tempDir: fileManager.getTempDir(),
        configured: true
      }
    } catch (error) {
      stats.local.configured = false
      console.error('获取本地文件状态失败:', error)
    }

    // 检查OSS配置状态
    try {
      const ossService = new AliyunOSSService()
      stats.oss.configured = true
    } catch (error) {
      stats.oss.configured = false
      stats.oss.error = error instanceof Error ? error.message : 'OSS服务未配置'
    }

    return NextResponse.json({
      success: true,
      stats
    })

  } catch (error) {
    console.error('获取文件状态API错误:', error)
    return NextResponse.json(
      { error: '获取状态失败' },
      { status: 500 }
    )
  }
}
